#include "gambler.h"
#include <iostream>
#include <cmath>
#include <functional>
#include <limits>

const size_t origin_buy_number = 100;

const double 
         gain = 0.7,    // 盈利时的收益率
         loss = 0.45,   // 亏损时的损失率
         win_prob = 0.92; // 胜率

double calculate_kelly_fraction(double gain, double loss, double win_prob) {
    if (loss <= 0 || win_prob < 0 || win_prob > 1) return 0.0;
    
    const double b = gain / loss;       // 计算赔率
    const double q = 1.0 - win_prob;     // 失败概率
    
    const double f = (b * win_prob - q) / b; // 凯利公式
    return std::fmax(f, 0.0);            // 负值时返回0
}



Gambler::Gambler():buy_quantity(origin_buy_number), buy_count(0), win_count(0) {
}

Gambler::~Gambler() {
}


// 赌徒买入
int Gambler::buy(const std::string& stock_code,  double price)
{
    // double buy_rate = calculate_kelly_fraction(gain, loss, win_prob);
    // std::cout<<"购买比例:"<<buy_rate <<std::endl;

    last_buy_price = price;
    current_stock_code = stock_code;
    ++buy_count;
    total_quantity+=buy_quantity;
    return buy_quantity;
}

// 赌徒卖出
int Gambler::sell(const std::string& stock_code,  double price)
{
    int stock_was_hold = total_quantity;
    if(price > last_buy_price)
    {
        buy_quantity=origin_buy_number;
        ++win_count;
    }
    else
    {
        // std::cout << "赌徒输钱了" << std::endl;
        // buy_quantity*=2;// 再翻倍就买不起, 该亏还是亏
    }
    // std::cout << "price:"<<price<<"\tlast_buy_price:"<<last_buy_price<<"\tbuy_quantity:"<<buy_quantity << std::endl;
    current_stock_code="";
    return stock_was_hold;
}

// 赌徒卖出
int Gambler::sell(const std::string& stock_code,  double price, size_t quantity)
{
    total_quantity-=quantity;
    return quantity;
}

// 现在持有哪只股票
std::string Gambler::getCurrentStockCode()
{
    return current_stock_code;
}
// 赢率
double Gambler::getWinRate()
{
    return (double)win_count / buy_count;
}
